<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-07-20
 * Time: 14:18
 */

namespace app\queue\job;


use app\constant\ActivesConst;
use app\constant\KanJiaConst;
use app\helper\ActiveHelper;
use app\model\AdminActives;
use app\model\AdminKanjiaOrder;
use app\model\AdminQueueMessage;
use think\Db;
use think\facade\Log;
use think\queue\Job;

class JobActivesStatusCheck{

    public function fire(Job $job, $data){

        print("<info>开始执行，数据为: " . json_encode($data) . "</info> \n");
        $model = AdminActives::get($data['id']);

        if($model){
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $this->failed($data);
                //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
                $job->delete();
            }else{
                try{
                    Db::startTrans();
                    $activeData = ActiveHelper::changeStatus($model->getData());
                    $model  = AdminActives::update($activeData);
                    if($model){
                        Log::write("更新活动状态成功".$activeData['status'],'error');
                        //如果是砍价活动，还需要去操作一下把砍价订单标识为结束
                        if($activeData['type']===ActivesConst::ACTIVE_TYPE_KJ){
                            (new AdminKanjiaOrder())->where(['goods_id'=>$activeData['id'],'tid'=>$activeData['tid'],'order_id'=>null])->update(['status'=>KanJiaConst::STATUS_CLOASE]);
                        }

                        //更新队列记录
                        $done = AdminQueueMessage::done($data['queue_id']);
                        if(!$done){
                            throw new \Exception('更新队列记录失败');
                        }
                        Db::commit();
                        $job->delete();
                    }else{
                        throw new \Exception('更新状态失败');
                    }
                }catch (\Exception $e){
                    Log::write("更新状态失败-".$e->getMessage(),'error');
                    Db::rollback();
                    //延时3秒执行
                    $job->release(3);
                }
            }
        }else{
            $job->delete();
        }
    }

    public function failed($data){
        Log::write("操作活动状态变更失败，且任务记录失败" . json_encode($data),'error');
    }

}